<template>
  <div class="operation-log">
    <!-- 页面标题 -->
    <div class="page-header">
      <i class="el-icon-menu" />
      <el-icon>
        <RefreshLeft />
      </el-icon>
      操作日志
    </div>
    <!-- 搜索区域 -->
    <div style="margin-left: 10px">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="操作类型" style="width: 300px">
          <el-select v-model="searchForm.type" placeholder="请选择操作类型" class="search-select">
            <el-option label="全部" value=""></el-option>
            <el-option label="用户登录" value="1"></el-option>
            <el-option label="用户退出登录" value="2"></el-option>
            <el-option label="添加用户" value="3"></el-option>
            <el-option label="重置密码" value="4"></el-option>
            <el-option label="禁用用户" value="5"></el-option>
            <el-option label="启用用户" value="6"></el-option>
            <el-option label="创建采购单" value="7"></el-option>
            <el-option label="确认采购单" value="8"></el-option>
            <el-option label="采购订单部分入库" value="9"></el-option>
            <el-option label="采购订单完成" value="10"></el-option>
            <el-option label="入库操作" value="11"></el-option>
            <el-option label="出库操作" value="12"></el-option>
            <el-option label="库存物品调整" value="13"></el-option>
            <el-option label="库存盘点" value="14"></el-option>
            <el-option label="调试操作" value="15"></el-option>
            <el-option label="新增食材" value="16"></el-option>
            <el-option label="停用食材" value="17"></el-option>
            <el-option label="启用食材" value="18"></el-option>
            <el-option label="新增仓库" value="19"></el-option>
            <el-option label="停用仓库" value="20"></el-option>
            <el-option label="启用仓库" value="21"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作人员">
          <el-input v-model="searchForm.user_name" placeholder="请输入操作人员" clearable />
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker v-model="searchForm.create_time" type="date" placeholder="请选择操作时间" format="YYYY-MM-DD"
            value-format="YYYY-MM-DD" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table :data="tableData" border stripe style="width: 100%" :header-cell-style="{
        background: '#f5f7fa',
        color: '#303133',
        fontWeight: '600',
      }">
        <!-- 序号 -->
        <el-table-column prop="index" label="序号" width="100" align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>

        <!-- 操作类型 -->
        <el-table-column prop="type" label="操作类型" width="150" align="center">
          <template #default="scope">
            <span :class="getOperationTypeClass(scope.row.op_type)" class="operation-type-tag">
              {{ getOperationTypeName(scope.row.op_type) }}
            </span>
          </template>
        </el-table-column>

        <!-- 操作描述 -->
        <el-table-column prop="description" label="操作描述" min-width="180" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.op_desc }}
          </template>
        </el-table-column>

        <!-- 操作人员 -->
        <el-table-column prop="operator" label="操作人员" width="180" align="center">
          <template #default="scope">
            {{ scope.row.user_name || scope.row.user_id }}
          </template>
        </el-table-column>

        <!-- 操作IP -->
        <el-table-column prop="ip" label="操作IP" width="180" align="center">
          <template #default="scope">
            {{ scope.row.ip }}
          </template>
        </el-table-column>

        <!-- 客户端类型 -->
        <el-table-column prop="client_type" label="客户端类型" width="120" align="center">
          <template #default="scope">
            <span :class="getClientTypeClass(scope.row.client_type)">
              {{ getClientTypeName(scope.row.client_type) }}
            </span>
          </template>
        </el-table-column>

        <!-- 操作时间 -->
        <el-table-column prop="time" label="操作时间" width="250" align="center">
          <template #default="scope">
            {{ utils.formatDate(scope.row.create_time, "YYYY-MM-DD HH:mm:ss") }}
          </template>
        </el-table-column>

        <!-- 操作列：仅系统管理员可见 -->
        <el-table-column v-if="isSystemAdmin" label="操作" width="100" align="center">
          <template #default="scope">
            <el-button type="text" size="small" @click="handleDelete(scope.row)" class="delete-button">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination background layout="total, sizes, prev, pager, next, jumper" :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" :total="total" @size-change="handleSizeChange"
        @current-change="handlePageChange" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useAuthStore } from "../../stores/userStore";
import { getLogs, deleteLog } from "../../api/Stslog";
import utils from "../../utils/index.js";

// 获取当前用户权限
const authStore = useAuthStore();
const isSystemAdmin = computed(() => {
  return authStore.user && authStore.user.role_id === 1;
});

// 搜索表单
const searchForm = ref({
  type: "",
  user_name: "",
  create_time: "",
});

// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 表格数据
const tableData = ref([]);

// 获取日志数据（已修正）
const fetchLogs = async () => {
  try {
    // 处理日期参数
    let startTime = undefined;
    let endTime = undefined;

    if (searchForm.value.create_time) {
      // 将日期转换为正确的格式
      startTime = searchForm.value.create_time + " 00:00:00";
      endTime = searchForm.value.create_time + " 23:59:59";
    }

    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      op_type: searchForm.value.type || undefined,
      user_name: searchForm.value.user_name || undefined,
      start_time: startTime,
      end_time: endTime,
    };

    // 清理空值参数
    Object.keys(params).forEach((key) => {
      if (params[key] === undefined) {
        delete params[key];
      }
    });

    const response = await getLogs(params);

    if (response.code === 0) {
      tableData.value = response.data.rows;
      total.value = response.data.total;
    } else {
      ElMessage.error(response.msg || "获取日志失败");
    }
  } catch (error) {
    ElMessage.error("获取日志失败，请检查网络或联系管理员");
    console.error(error);
  }
};
// 初始化加载
onMounted(() => {
  fetchLogs();
});

// 分页事件
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchLogs();
};

const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchLogs();
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchLogs();
};

// 重置
const resetSearch = () => {
  searchForm.value = {
    type: "",
    user_name: "",
    create_time: "",
  };
  currentPage.value = 1;
  fetchLogs();
};

// 删除日志
const handleDelete = async (row) => {
  ElMessageBox.confirm(`确定要删除这条操作日志记录吗？`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const response = await deleteLog(row.id);
        if (response.code === 0) {
          ElMessage.success("删除成功");
          fetchLogs(); // 刷新数据
        } else {
          ElMessage.error(response.msg || "删除失败");
        }
      } catch (error) {
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 映射客户端类型到中文名称
const getClientTypeName = (type) => {
  const map = {
    WEB: "Web",
    ANDROID: "Android",
    IOS: "iOS",
    OTHER: "其他",
  };
  return map[type] || type;
};

// 映射客户端类型到样式类
const getClientTypeClass = (type) => {
  const classes = {
    WEB: "web",
    ANDROID: "android",
    IOS: "ios",
    OTHER: "other",
  };
  return classes[type] || "";
};

// 映射操作类型到中文名称和样式
const getOperationTypeName = (opType) => {
  const map = {
    1: "用户登录",
    2: "用户退出登录",
    3: "添加用户",
    4: "重置密码",
    5: "禁用用户",
    6: "启用用户",
    7: "创建采购单",
    8: "确认采购单",
    9: "采购订单部分入库",
    10: "采购订单完成",
    11: "入库操作",
    12: "出库操作",
    13: "库存物品调整",
    14: "库存盘点",
    15: "调试操作",
    16: "新增食材",
    17: "停用食材",
    18: "启用食材",
    19: "新增仓库",
    20: "停用仓库",
    21: "启用仓库",
  };
  return map[opType] || "未知";
};

const getOperationTypeClass = (opType) => {
  const classes = {
    1: "login",
    2: "logout",
    3: "user",
    4: "user",
    5: "user",
    6: "user",
    7: "purchase",
    8: "purchase",
    9: "inbound",
    10: "inbound",
    11: "inbound",
    12: "outbound",
    13: "stock",
    14: "stock",
    15: "debug",
    16: "ingredient",
    17: "ingredient",
    18: "ingredient",
    19: "warehouse",
    20: "warehouse",
    21: "warehouse",
  };
  return classes[opType] || "";
};
</script>

<style scoped>
.web {
  background-color: #e6f7ff;
  color: #1890ff;
}

.android {
  background-color: #f0f9eb;
  color: #67c23a;
}

.ios {
  background-color: #fff1e6;
  color: #f56c6c;
}

.other {
  background-color: #f5f5f5;
  color: #909399;
}

/* 样式保持不变 */
.operation-log {
  background-color: white;
  min-height: 100vh;
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
}

.operation-type-tag {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  display: inline-block;
}

.purchase {
  background-color: #e6f7ff;
  color: #1890ff;
}

.inbound {
  background-color: #f0f9eb;
  color: #67c23a;
}

.outbound {
  background-color: #fff1e6;
  color: #f56c6c;
}

.stock{
  background-color: blanchedalmond;
  color: #000;
}

.user {
  background-color: #fff5f5;
  color: #f56c6c;
}

.login {
  background-color: #e6f7ff;
  color: #1890ff;
}

.logout {
  background-color: #f5f5f5;
  color: #909399;
}

.debug {
  background-color: #f5f5f5;
  color: #999;
}

.ingredient {
  background-color: #f0f0ff;
  color: #6666cc;
}

.warehouse {
  background-color: #f0fff0;
  color: #339966;
}

.default {
  background-color: #f0f0f0;
  color: #666666;
}

.delete-button {
  color: #f56c6c;
}

.delete-button:hover {
  color: #ff0000;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.pagination-container .el-pagination {
  margin: 0;
}
</style>
